<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hash数据持久化</title>
</head>

<body>
  <div id="title">
    <button data-url="/music">音乐</button>
    <button data-url="/movie">电影</button>
    <button data-url="/news">新闻</button>
  </div>
  <div id="view">
  </div>
 
  <script>
    //获取按钮与视图dom元素
    const oBtns = document.querySelectorAll('#title button')
    const oView = document.getElementById("view")
   //创建路由表
    const routes = [{
      path: "/music", content: "晚夜微雨问海棠"
    }, {
      path: "/movie", content: "加勒比海盗3：世界尽头"
    }, {
      path: "/news", content: "外交部召见美国驻华大使"
    },

    ]
    //遍历按钮，绑定点击事件
    for (let i = 0; i < oBtns.length; i++) {
      oBtns[i].onclick = function () {
        //使用H5提供的方法，每当按钮触发便把自定义属性里存的地址给到当前路径
        history.pushState(null, null, this.dataset.url)
        //地址改变后直接改变视图
        routes.forEach(route => {
          if (route.path === this.dataset.url) {
            oView.textContent = route.content
          }
        })
      }
    }
    //历史条目变化的时候触发的回调函数
    window.onpopstate = function () {
      routes.forEach(route => {
        //根据当前的路径名改变视图
        if (route.path === location.pathname) {
          oView.textContent = route.content
        }
      })
    }





  </script>
</body>

</html>